package com.blocks.blocks;

import com.blocks.ScriptBlocksApplication;
import com.blocks.controller.BlockEvent;
import com.blocks.gui.BlockListGroup;
import com.blocks.model.BlockSides;
import com.jme3.bounding.BoundingVolume;
import com.jme3.collision.CollisionResult;
import com.jme3.collision.CollisionResults;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.scene.Node;

/**
 * This block is used for events when something comes in contact with it. It
 * will send out a event Mostly use to get to point B
 * 
 * 
 */
public class TriggerBlock extends Block {
	public TriggerBlock() {
		super();
	}

	public TriggerBlock(String name, Long masterId) {
		super(name, masterId);
		this.setBlockListGroup(BlockListGroup.GAME);
	}

	@Override
	public void init() {
		setTextureRow(0.0f);
		setTextureColumn(9.0f);
		super.init();

	}

	@Override
	public void updateLogicalState(float tpf) {
		boolean found = false;
		super.updateLogicalState(tpf);
		if (this.isPowered()) {
			CollisionResults results = new CollisionResults();
			BoundingVolume bv = this.getWorldBound();
			for (Long masterId : ScriptBlocksApplication.getInstance()
					.getMasterBlockMap().keySet()) {
				if (masterId != this.getMasterId()) {
					MasterBlock masterBlock = ScriptBlocksApplication
							.getInstance().getMasterBlock(masterId);
					masterBlock.collideWith(bv, results);
					if (results.size() > 0) {
						for (CollisionResult collisionResult : results) {
							if (collisionResult.getGeometry() != null) {
								Node hitNode = collisionResult.getGeometry()
										.getParent();
								float distance = collisionResult.getDistance();
								if (distance <= 2.0f && hitNode != null) {

									if (hitNode != null
											&& Block.class
													.isAssignableFrom(hitNode
															.getClass())) {
										Block focusBlock = (Block) hitNode;
										if (focusBlock.getMasterId().compareTo(
												this.getMasterId()) != 0) {
											// System.out.println("TRIGGERD BY"
											// + focusBlock.getName() +
											// "MASTER ID"+this.getMasterId()
											// +"!=" +focusBlock.getMasterId()
											// );
											this.getMaterial().setColor(
													"Color", ColorRGBA.Pink);
											trigger();
											found =true;
											break;
										}
									}

								}

							}
						}
					}
				}
			}
		}
		if(!isPowered()||!found){
			this.getMaterial().setColor("Color",
					ColorRGBA.Gray);
		}

	}

	public void trigger() {
		ScriptBlocksApplication.getInstance().addBlockEvent(BlockEvent.LEVEL_COMPLETED);

	}

}
